<!DOCTYPE html>
<html lang="en">
  <head>
    <title>
        Java-framework-SpringCloud-5 - rulerLwx Blog
      </title>
        <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    
    <meta name="theme-color" content="#000000" />
    
    <meta http-equiv="window-target" content="_top" />
    
    
    <meta name="description" content="zuul-路由网关 zuul概述 官方文档：https://github.com/Netflix/zuul/wiki/Getting-Start" />
    <meta name="generator" content="Hugo 0.73.0 with theme pure" />
    <title>Java-framework-SpringCloud-5 - rulerLwx Blog</title>
    
    
    <link rel="stylesheet" href="https://rulerLwx.gitee.io/css/style.min.c4bc7071f132c964c2116bca53b392933f377e5ca7b7051ed245187c621a2d3e.css">
    
    <link rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/9.15.10/styles/github.min.css" async>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.css" async>
    <meta property="og:title" content="Java-framework-SpringCloud-5" />
<meta property="og:description" content="zuul-路由网关 zuul概述 官方文档：https://github.com/Netflix/zuul/wiki/Getting-Start" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://rulerLwx.gitee.io/2019/08/java-framework-springcloud-5/" />
<meta property="article:published_time" content="2019-08-25T12:11:30+08:00" />
<meta property="article:modified_time" content="2019-08-25T12:11:30+08:00" />
<meta itemprop="name" content="Java-framework-SpringCloud-5">
<meta itemprop="description" content="zuul-路由网关 zuul概述 官方文档：https://github.com/Netflix/zuul/wiki/Getting-Start">
<meta itemprop="datePublished" content="2019-08-25T12:11:30&#43;08:00" />
<meta itemprop="dateModified" content="2019-08-25T12:11:30&#43;08:00" />
<meta itemprop="wordCount" content="3346">



<meta itemprop="keywords" content="" /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Java-framework-SpringCloud-5"/>
<meta name="twitter:description" content="zuul-路由网关 zuul概述 官方文档：https://github.com/Netflix/zuul/wiki/Getting-Start"/>

    <!--[if lte IE 9]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
      <![endif]-->

    <!--[if lt IE 9]>
        <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
      <![endif]-->
  </head>

  
  

  <body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage"><header class="header" itemscope itemtype="http://schema.org/WPHeader">
    <div class="slimContent">
      <div class="navbar-header">
        <div class="profile-block text-center">
          <a id="avatar" href="https://gitee.com/rulerLwx" target="_blank">
            <img class="img-circle img-rotate" src="https://rulerLwx.gitee.io/avatar.png" width="200" height="200">
          </a>
          <h2 id="name" class="hidden-xs hidden-sm">rulerLwx</h2>
          <h3 id="title" class="hidden-xs hidden-sm hidden-md">thinking...</h3>
          <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i>Guangzhou, China</small>
        </div><div class="search" id="search-form-wrap">
    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="Search" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i
                        class="icon icon-search"></i></button>
            </span>
        </div>
        <div class="ins-search">
            <div class="ins-search-mask"></div>
            <div class="ins-search-container">
                <div class="ins-input-wrapper">
                    <input type="text" class="ins-search-input" placeholder="Type something..."
                        x-webkit-speech />
                    <button type="button" class="close ins-close ins-selectable" data-dismiss="modal"
                        aria-label="Close"><span aria-hidden="true">×</span></button>
                </div>
                <div class="ins-section-wrapper">
                    <div class="ins-section-container"></div>
                </div>
            </div>
        </div>
    </form>
</div>
        <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      </div>
      <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
        <ul class="nav navbar-nav main-nav">
            <li class="menu-item menu-item-home">
                <a href="/">
                    <i class="icon icon-home-fill"></i>
                  <span class="menu-title">Home</span>
                </a>
            </li>
            <li class="menu-item menu-item-archives">
                <a href="/posts/">
                    <i class="icon icon-archives-fill"></i>
                  <span class="menu-title">Archives</span>
                </a>
            </li>
            <li class="menu-item menu-item-categories">
                <a href="/categories/">
                    <i class="icon icon-folder"></i>
                  <span class="menu-title">Categories</span>
                </a>
            </li>
            <li class="menu-item menu-item-tags">
                <a href="/tags/">
                    <i class="icon icon-tags"></i>
                  <span class="menu-title">Tags</span>
                </a>
            </li>
            <li class="menu-item menu-item-about">
                <a href="/about/">
                    <i class="icon icon-cup-fill"></i>
                  <span class="menu-title">About</span>
                </a>
            </li>
        </ul>
      </nav>
    </div>
  </header>

<aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">Board</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">enjoy~
            </div>
        </div>
    </div>
</div>

      <div class="widget">
    <h3 class="widget-title"> Categories</h3>
    <div class="widget-body">
        <ul class="category-list">
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-framework/" class="category-list-link">java-framework</a><span class="category-list-count">38</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-front-end/" class="category-list-link">java-front-end</a><span class="category-list-count">11</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-se/" class="category-list-link">java-se</a><span class="category-list-count">21</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-senior/" class="category-list-link">java-senior</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/linux/" class="category-list-link">linux</a><span class="category-list-count">13</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/tools/" class="category-list-link">tools</a><span class="category-list-count">1</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%8A%80%E6%9C%AF%E6%9D%82%E7%83%A9/" class="category-list-link">技术杂烩</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="category-list-link">数据库</a><span class="category-list-count">15</span></li>
        </ul>
    </div>
</div>
      <div class="widget">
    <h3 class="widget-title"> Tags</h3>
    <div class="widget-body">
        <ul class="tag-list">
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/jvm/" class="tag-list-link">jvm</a><span
                    class="tag-list-count">1</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" class="tag-list-link">多线程</a><span
                    class="tag-list-count">2</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" class="tag-list-link">网络编程</a><span
                    class="tag-list-count">3</span></li>
            
        </ul>

    </div>
</div>
      
<div class="widget">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget-body">
        <ul class="recent-post-list list-unstyled no-thumbnail">
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%87%AA%E5%B7%B1%E5%8A%A8%E6%89%8B%E4%B8%80%E6%89%B9%E9%87%8F%E7%A7%BB%E5%8A%A8%E9%87%8D%E5%91%BD%E5%90%8D%E6%96%87%E4%BB%B6/" class="title">自己动手（一）——批量移动、重命名文件</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-27 17:50:02 &#43;0800 CST" itemprop="datePublished">2020-07-27</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E5%85%B3%E4%BA%8Einteger%E7%9A%84-128~127%E7%BC%93%E5%AD%98/" class="title">关于Integer的 -128~127缓存</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-11 16:56:21 &#43;0800 CST" itemprop="datePublished">2020-07-11</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98/" class="title">跨域问题</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-08 22:41:12 &#43;0800 CST" itemprop="datePublished">2020-07-08</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E4%B8%AA%E4%BA%BA%E5%8D%9A%E5%AE%A2%E6%90%AD%E5%BB%BA/" class="title">个人博客搭建</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-05 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-05</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/mongodb-1/" class="title">MonggoDB-1</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-03 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-03</time>
                    </p>
                </div>
            </li>
        </ul>
    </div>
</div>
  </div>
</aside>

    
    
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <h4 class="toc-title">Catalogue</h4>
    <nav id="toc" class="js-toc toc">

    </nav>
  </div>
</aside>
<main class="main" role="main"><div class="content">
  <article id="-" class="article article-type-" itemscope
    itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      <h1 itemprop="name">
  <a
    class="article-title"
    href="/2019/08/java-framework-springcloud-5/"
    >Java-framework-SpringCloud-5</a
  >
</h1>

      <div class="article-meta">
        
<span class="article-date">
  <i class="icon icon-calendar-check"></i>&nbsp;
<a href="https://rulerLwx.gitee.io/2019/08/java-framework-springcloud-5/" class="article-date">
  <time datetime="2019-08-25 12:11:30 &#43;0800 CST" itemprop="datePublished">2019-08-25</time>
</a>
</span>
<span class="article-category">
  <i class="icon icon-folder"></i>&nbsp;
  <a class="article-category-link" href="/categories/java-framework/"> Java-framework </a>
</span>

        <span class="post-comment"><i class="icon icon-comment"></i>&nbsp;<a href="/2019/08/java-framework-springcloud-5/#comments"
            class="article-comment-link">Comments</a></span>
		<span class="post-wordcount hidden-xs" itemprop="wordCount">Word Count: 3346words</span>
		<span class="post-readcount hidden-xs" itemprop="timeRequired">Read Count: 7minutes </span>
      </div>
    </div>
    <div class="article-entry marked-body js-toc-content" itemprop="articleBody">
      <h1 id="zuul-路由网关">zuul-路由网关</h1>
<h2 id="zuul概述">zuul概述</h2>
<p>官方文档：https://github.com/Netflix/zuul/wiki/Getting-Started</p>
<p>Zuul包含了对请求的路由和过滤两个最主要的功能：</p>
<ul>
<li>路由：负责将外部请求转发到具体的微服务实例上，是实现外部访问统一入口的基础</li>
<li>过滤：负责对请求的处理过程进行干预，是实现请求校验、服务聚合等功能的基础</li>
</ul>
<p>Zuul和Eureka进行整合，将Zuul自身注册为Eureka服务治理下的应用，同时从Eureka中获得其他微服务的消息，也即以后的访问微服务都是通过Zuul跳转后获得。</p>
<p>注意：Zuul服务最终还是会注册进Eureka</p>
<p>提供=代理+路由+过滤三大功能</p>
<h2 id="zuul路由基本配置">zuul路由基本配置</h2>
<p>1）新建模块 microservicecloud-zuul-geteway-9527</p>
<p>2）依赖</p>
<pre><code class="language-xml">    &lt;dependency&gt;
     &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
     &lt;artifactId&gt;spring-cloud-starter-eureka&lt;/artifactId&gt;
   &lt;/dependency&gt;
   &lt;dependency&gt;
     &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
     &lt;artifactId&gt;spring-cloud-starter-zuul&lt;/artifactId&gt;
   &lt;/dependency&gt;
</code></pre>
<p>3）yml</p>
<pre><code class="language-yml">server: 
  port: 9527
 
spring: 
  application:
    name: microservicecloud-zuul-gateway
 
eureka: 
  client: 
    service-url: 
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka,http://eureka7003.com:7003/eureka  
  instance:
    instance-id: gateway-9527.com
    prefer-ip-address: true 
 
info:
  app.name: atguigu-microcloud
  company.name: www.atguigu.com
  build.artifactId: $project.artifactId$
  build.version: $project.version$
</code></pre>
<p>4）修改host</p>
<pre><code>127.0.0.1 myzuul9527.com
</code></pre>
<p>5）主启动类使用注解@EnableZuulProxy</p>
<pre><code class="language-java">@SpringBootApplication
@EnableZuulProxy
public class Zuul_9527_StartSpringCloudApp
{
  public static void main(String[] args)
  {
   SpringApplication.run(Zuul_9527_StartSpringCloudApp.class, args);
  }
}
</code></pre>
<p>6）测试</p>
<ul>
<li>启动三个eureka</li>
<li>启动一个服务提供者：microservicecloud-provider-dept-8001</li>
<li>启动一个路由：microservicecloud-zuul-geteway-9527</li>
</ul>
<p>不用路由，访问：http://localhost:8001/dept/get/2</p>
<p>使用路由，访问：http://myzuul9527.com:9527/microservicecloud-dept/dept/get/2</p>
<h2 id="zuul路由规则">zuul路由规则</h2>
<p>优化 microservicecloud-zuul-geteway-9527 模块，用别名代替实例名，application.yml添加以下配置：</p>
<pre><code>zuul: 
  prefix: /atguigu
  ignored-services: &quot;*&quot;
  routes: 
    mydept.serviceId: microservicecloud-dept
    mydept.path: /mydept/**
</code></pre>
<p>解释：</p>
<ul>
<li>prefix：设置公共统一前缀</li>
<li>ignored-services：忽略原真实服务名，忽略多个时用 *</li>
</ul>
<p>测试：</p>
<ul>
<li>通过路由访问：http://myzuul9527.com:9527/atguigu/mydept/dept/get/2</li>
<li>通过原路径访问：http://myzuul9527.com:9527/atguigu/microservicecloud-dept/dept/get/2
，（设置 ignored-services: &ldquo;*&rdquo; 后访问不到，若要看效果，需去掉）</li>
</ul>
<p>注意：ignored-services: &ldquo;*&quot;，要写 &quot;&rdquo;</p>
<h1 id="springcloud-config-分布式配置中心">SpringCloud config 分布式配置中心</h1>
<h2 id="概述">概述</h2>
<p><img src="https://oscimg.oschina.net/oscnet/up-c2a8ad21b8fb7dc6abfc36ddaa92d2174c1.png" alt=""></p>
<p>SpringCloud Config 为微服务架构中的微服务提供集中化的外部配置支持，中心化的外部配置。</p>
<p>SpringCloud Config 分为客户端、服务端，服务端即是<strong>分布式配置中心</strong></p>
<h2 id="springcloud-config-服务端与github通信">SpringCloud Config 服务端与github通信</h2>
<p>步骤：</p>
<p>1）在github上创建一个公共的新的仓库：microservicecloud-config</p>
<p>2）在本地电脑上clone新建的仓库，在克隆好的目录中新建一个application.yml，内容如下：</p>
<pre><code>spring:
  profiles:
    active: -dev
---

spring:
  profiles: dev #开发环境
  application:
    name: microservicecloud-config-atguigu-dev

---
spring:
  profiles: test # 测试环境
  application:
    name: microservicecloud-config-atguigu-test

# 文件需要用 UTF-8 编码保存
</code></pre>
<p>注意：仓库中的<strong>application.yml必须用UTF-8编码保存</strong>，否则其它服务读取时将会报错</p>
<p>3）将新建的application.yml推送到github</p>
<pre><code>git clone https://github.com/wolf-lea/microservicecloud-config.git
git add .
git commit -m &quot;add&quot; .
git push https://github.com/wolf-lea/microservicecloud-config.git 或 git push origin master
</code></pre>
<p>4）新建模块：microservicecloud-config-3344</p>
<p>pom.xml依赖</p>
<pre><code>		&lt;!-- springCloud Config --&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
			&lt;artifactId&gt;spring-cloud-config-server&lt;/artifactId&gt;
		&lt;/dependency&gt;
</code></pre>
<p>application.yml</p>
<pre><code>server:
  port: 3344

spring:
  application:
    name:  microservicecloud-config
  cloud:
    config:
      server:
        git:
          uri: https://github.com/wolf-lea/microservicecloud-config.git
</code></pre>
<p>主启动类使用注解 @EnableConfigServer</p>
<pre><code class="language-java">@SpringBootApplication
@EnableConfigServer
public class Config_3344_StartSpringCloudApp
{
	public static void main(String[] args)
	{
		SpringApplication.run(Config_3344_StartSpringCloudApp.class, args);
	}
}
</code></pre>
<p>5）修改host</p>
<pre><code>127.0.0.1 config-3344.com
</code></pre>
<p>6）测试</p>
<ul>
<li>启动 microservicecloud-config-3344</li>
<li>访问 <a href="http://config-3344.com">http://config-3344.com</a>:3344/application-dev.yml</li>
<li>访问 <a href="http://config-3344.com">http://config-3344.com</a>:3344/application-test.yml</li>
<li>访问 <a href="http://config-3344.com">http://config-3344.com</a>:3344/application-abcdefghijklmnopqrstuvwzyx.yml</li>
</ul>
<p>知识：配置读取规则</p>
<p><img src="https://oscimg.oschina.net/oscnet/up-d9099bd4d0669688fb7d7f96d658244ea30.png" alt=""></p>
<p>7）总结</p>
<p>这个示例是单独的工程，不需要注册到eureka（以后的开发需要），不需要调用其它服务，只需要提供一个git地址</p>
<p>8）技巧</p>
<p>将配置文件放进文件夹，服务端根据客户端需要的配置文件名搜索配置的文件夹列表</p>
<p>多了 search-paths ，示例：</p>
<pre><code class="language-yml">server:
  port: 3344

spring:
  application:
    name:  microservicecloud-config
  cloud:
    config:
      server:
        git:
          uri: https://github.com/wolf-lea/microservicecloud-config.git
          search-paths: config # 可以将配置文件放进文件夹，多个文件夹可以用逗号分隔
</code></pre>
<p>参考：https://blog.csdn.net/myth_g/article/details/90344374</p>
<h2 id="springcloud-config-客户端通过服务端获得github上的配置">SpringCloud Config 客户端通过服务端获得github上的配置</h2>
<p><a href="https://www.bilibili.com/video/av22623176?p=49">https://www.bilibili.com/video/av22623176?p=49</a></p>
<p>步骤：</p>
<p>1）在本地git仓库新建 microservicecloud-config-client.yml 文件，内容如下，并提交到github</p>
<pre><code>spring:
  profiles:
    active: -dev
---
server:
  port: 8201
spring:
  profiles: dev
  application:
    name: microservicecloud-config-client
eureka:
  client:
    service-url:
      defaultZone: http://eureka-dev.com:7001/eureka/
---
server:
  port: 8202
spring:
  profiles: test
  application:
    name: microservicecloud-config-client
eureka:
  client:
    service-url:
      defaultZone: http://eureka-test.com:7001/eureka/
</code></pre>
<p>2）新建模块 microservicecloud-config-client-3355</p>
<p>pom</p>
<pre><code>        &lt;!--config 客户端--&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-config&lt;/artifactId&gt;
        &lt;/dependency&gt;
</code></pre>
<p>bootstrap.yml，系统级，优先级更高</p>
<pre><code>spring:
  cloud:
    config:
      name: microservicecloud-config-client #需要从github上读取的资源名称，注意没有yml后缀名
      profile: test   #本次访问的配置项
      label: master   
      uri: http://config-3344.com:3344  #本微服务启动后先去找3344号服务，通过SpringCloudConfig获取GitHub的服务地址
</code></pre>
<p>application.yml，用户级</p>
<pre><code>spring:
  application:
    name: microservice-config-client
</code></pre>
<p>3）修改host</p>
<p>这一步不是必须的</p>
<pre><code>127.0.0.1 config-client.com
</code></pre>
<p>4）编写rest风格 controller</p>
<pre><code class="language-java">@RestController
public class ConfigClientRest
{

    @Value(&quot;${spring.application.name}&quot;)
    private String applicationName;

    @Value(&quot;${eureka.client.service-url.defaultZone}&quot;)
    private String eurekaServers;

    @Value(&quot;${server.port}&quot;)
    private String port;

    @RequestMapping(&quot;/config&quot;)
    public String getConfig()
    {
        String str = &quot;applicationName: &quot; + applicationName + &quot;\t eurekaServers:&quot; + eurekaServers + &quot;\t port: &quot; + port;
        System.out.println(&quot;******str: &quot; + str);
        return &quot;applicationName: &quot; + applicationName + &quot;\t eurekaServers:&quot; + eurekaServers + &quot;\t port: &quot; + port;
    }
}
</code></pre>
<p>总结：此处@Value的值是从中心服务器中获取，中心服务器又从github上获取</p>
<p>5）测试</p>
<ul>
<li>启动3344服务端，自测：http://config-3344.com:3344/application-dev.yml</li>
<li>启动3355客户端，测试：</li>
</ul>
<p>如果bootstrap.yml的profiles:dev，则访问的是：http://config-client.com:8201/config</p>
<p>如果bootstrap.yml的profiles:test，则访问的是：http://config-client.com:8202/config</p>
<h2 id="springcloud-config-配置实战示例">SpringCloud Config 配置实战示例</h2>
<p><a href="https://www.bilibili.com/video/av22623176?p=50">https://www.bilibili.com/video/av22623176?p=50</a></p>
<p>步骤：</p>
<p>1）本地git仓库新建如下两个yml配置文件，并提交到github</p>
<p>microservicecloud-config-eureka-client.yml：</p>
<pre><code class="language-yml">spring:
  profiles:
    active:
      - dev
---
server:
  port: 7001
spring:
  profiles: dev
  application:
    name: microservicecloud-config-eureka-client
eureka:
  instance:
    hostname: eureka7001.com
  client:
    register-with-eureka: false # 自己不注册进 eureka
    fetch-registry: false # 不通过 eureka 获取注册信息
    service-url:
      defaultZone: http://eureka7001:7001/eureka/
---
server:
  port: 7001
spring:
  profiles: test
  application:
    name: microservicecloud-config-eureka-client
eureka:
  instance:
    hostname: eureka7001.com
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
      defaultZone: http://eureka7001:7001/eureka/
</code></pre>
<p>microservicecloud-config-dept-client.yml：</p>
<pre><code class="language-yml">spring:
  profiles:
    active:
      - dev
---
server:
  port: 8001
spring:
  profiles: dev
  application:
    name: microservicecloud-config-dept-client
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource            # 当前数据源操作类型
    driver-class-name: org.gjt.mm.mysql.Driver              # mysql驱动包
    url: jdbc:mysql://localhost:3306/cloudDB01              # 数据库名称
    username: root
    password: root
    dbcp2:
      min-idle: 5                                           # 数据库连接池的最小维持连接数
      initial-size: 5                                       # 初始化连接数
      max-total: 5                                          # 最大连接数
      max-wait-millis: 200                                  # 等待连接获取的最大超时时间
mybatis:
  config-location: classpath:mybatis/mybatis.cfg.xml        # mybatis配置文件所在路径
  type-aliases-package: com.atguigu.springcloud.entity    # 所有Entity别名类所在包
  mapper-locations:
    - classpath:mybatis/mapper/**/*.xml                       # mapper映射文件

eureka:
  client:
    service-url:
      defaultZone:http://eureka7001.com:7001/eureka/
  instance:
    instance-id: dept-8001.com
    prefer-ip-address: true
---
server:
  port: 8001
spring:
  profiles: dev
  application:
    name: microservicecloud-config-dept-client
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource            # 当前数据源操作类型
    driver-class-name: org.gjt.mm.mysql.Driver              # mysql驱动包
    url: jdbc:mysql://localhost:3306/cloudDB02              # 数据库名称
    username: root
    password: root
    dbcp2:
      min-idle: 5                                           # 数据库连接池的最小维持连接数
      initial-size: 5                                       # 初始化连接数
      max-total: 5                                          # 最大连接数
      max-wait-millis: 200                                  # 等待连接获取的最大超时时间
mybatis:
  config-location: classpath:mybatis/mybatis.cfg.xml        # mybatis配置文件所在路径
  type-aliases-package: com.atguigu.springcloud.entity    # 所有Entity别名类所在包
  mapper-locations:
    - classpath:mybatis/mapper/**/*.xml                       # mapper映射文件

eureka:
  client:
    service-url:
      defaultZone:http://eureka7001.com:7001/eureka/
  instance:
    instance-id: dept-8001.com
    prefer-ip-address: true
</code></pre>
<p>2）新建模块 microservicecloud-config-eureka-client-7001</p>
<p>pom</p>
<pre><code class="language-xml">        &lt;!-- SpringCloudConfig配置 --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-config&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-eureka-server&lt;/artifactId&gt;
        &lt;/dependency&gt;
</code></pre>
<p>bootstrap.yml</p>
<pre><code class="language-yml">spring: 
  cloud: 
    config: 
      name: microservicecloud-config-eureka-client     #需要从github上读取的资源名称，注意没有yml后缀名
      profile: dev 
      label: master 
      uri: http://config-3344.com:3344      #SpringCloudConfig获取的服务地址


</code></pre>
<p>application.yml</p>
<pre><code class="language-yml">spring:
  application:
    name: microservicecloud-config-eureka-client
</code></pre>
<p>主启动类：</p>
<pre><code class="language-java">/**
 * EurekaServer服务器端启动类,接受其它微服务注册进来
 */
@SpringBootApplication
@EnableEurekaServer
public class Config_Git_EurekaServerApplication
{
	public static void main(String[] args) {
		SpringApplication.run(Config_Git_EurekaServerApplication.class, args);
	}
}
</code></pre>
<p>模块自测：</p>
<ul>
<li>先启动 microservicecloud-config-3344</li>
<li>再启动 microservicecloud-config-eureka-client-7001</li>
<li>访问：http://eureka7001.com:7001</li>
</ul>
<p>总结：</p>
<ol>
<li>这是一个注册进eureka的config客户端</li>
<li>它的配置文件是从3344服务端获取，而3344又从git仓库获取</li>
</ol>
<p>3）新建模块：microservicecloud-config-dept-client-8001 （参考之前的8001工程）</p>
<p>pom</p>
<pre><code class="language-xml">
</code></pre>
<p>bootstrap.yml</p>
<pre><code class="language-yml">spring:
  cloud:
    config:
      name: microservicecloud-config-dept-client #需要从github上读取的资源名称，注意没有yml后缀名
      #profile配置是什么就取什么配置dev or test
      #profile: dev
      profile: test
      label: master
      uri: http://config-3344.com:3344  #SpringCloudConfig获取的服务地址
</code></pre>
<p>application.yml</p>
<pre><code class="language-yml">spring:
  application:
    name: microservicecloud-dept
</code></pre>
<p>启动类：</p>
<pre><code class="language-java">@SpringBootApplication
@EnableEurekaClient // 自动注册进 eureka 服务中
@EnableDiscoveryClient // 服务发现
public class DeptProvider8001_App {
    public static void main(String[] args) {
        SpringApplication.run(DeptProvider8001_App.class, args);
    }
}
</code></pre>
<p>测试</p>
<ul>
<li>启动配置中心： microservicecloud-config-3344</li>
<li>启动 eureka 服务中心：microservicecloud-config-eureka-client-7001</li>
<li>启动服务提供者：microservicecloud-config-dept-client-8001</li>
<li>访问 http://localhost:8001/dept/list ，看数据库是clouddb01还是clouddb02，然后切换 服务提供者 的bootstrap.yml中的profile: test/dev，再测</li>
</ul>
<h1 id="总结回顾">总结回顾</h1>
<p>架构图：</p>
<p><img src="https://oscimg.oschina.net/oscnet/up-077ba04cfe2835406a2a9258b46e97ec38a.png" alt=""></p>

    </div>
    <div class="article-footer">
<blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-link hidden-xs">
      <strong>Permalink: </strong>
      <a href="https://rulerLwx.gitee.io/2019/08/java-framework-springcloud-5/" title="Java-framework-SpringCloud-5" target="_blank" rel="external">https://rulerLwx.gitee.io/2019/08/java-framework-springcloud-5/</a>
    </li>
    <li class="post-copyright-license">
      <strong>License：</strong><a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN</a>
    </li>
  </ul>
</blockquote>

<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://gitee.com/rulerLwx" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://rulerLwx.gitee.io/avatar.png" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://gitee.com/rulerLwx" target="_blank"><span class="text-dark">rulerLwx</span><small class="ml-1x">thinking...</small></a></h3>
        <div>Good Good Study, Day Day Up~</div>
      </div>
    </figure>
  </div>
</div>
    </div>
  </article>
<section id="comments">
    <div id="vcomments"></div>
</section>

</div><nav class="bar bar-footer clearfix" data-stick-bottom>
    <div class="bar-inner">
        <ul class="pager pull-left">
            <li class="prev">
                <a href="https://rulerLwx.gitee.io/2019/08/java-framework-springcloud-4/" title="Java-framework-SpringCloud-4"><i
                        class="icon icon-angle-left"
                        aria-hidden="true"></i><span>&nbsp;&nbsp;Older</span></a>
            </li>
            <li class="next">
                <a href="https://rulerLwx.gitee.io/2020/07/idea/"
                    title="IDEA"><span>Newer&nbsp;&nbsp;</span><i
                        class="icon icon-angle-right" aria-hidden="true"></i></a>
            </li>
            
            <li class="toggle-toc">
                <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false"
                    title="Catalogue" role="button">
                    <span>[&nbsp;</span><span>Catalogue</span>
                    <i class="text-collapsed icon icon-anchor"></i>
                    <i class="text-in icon icon-close"></i>
                    <span>]</span>
                </a>
            </li>
        </ul>
        <div class="bar-right">
            <div class="share-component" data-sites="weibo,qq,wechat"
                data-mobile-sites="weibo,qq,qzone"></div>
        </div>
    </div>
</nav>

</main><footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
<ul class="social-links">
    <li><a href="https://gitee.com/rulerLwx" target="_blank" title="gitee" data-toggle=tooltip data-placement=top >
            <i class="icon icon-gitee"></i></a></li>
    <li><a href="https://github.com/wolf-lea" target="_blank" title="github" data-toggle=tooltip data-placement=top >
            <i class="icon icon-github"></i></a></li>
</ul>
  <div class="copyright">
    &copy;2017  -
    2020
    <div class="publishby">
        Theme by <a href="https://github.com/xiaoheiAh" target="_blank"> xiaoheiAh </a>base on<a href="https://github.com/xiaoheiAh/hugo-theme-pure" target="_blank"> pure</a>.
    </div>
  </div>
</footer>

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_SVG"></script>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
            showMathMenu: false, //disables context menu
            tex2jax: {
            inlineMath: [ ['$','$'], ['\\(','\\)'] ]
           }
    });
</script>


<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
<script>
    window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/highlight.min.js"></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/python.min.js" defer></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/javascript.min.js" defer></script><script>
    hljs.configure({
        tabReplace: '    ', 
        classPrefix: ''     
        
    })
    hljs.initHighlightingOnLoad();
</script>
<script src="https://rulerLwx.gitee.io/js/application.min.bdeb64b910570b6c41badc6a05b7afb0c8ad9efd8525de3c7257d59e786326a3.js"></script>
<script src="https://rulerLwx.gitee.io/js/plugin.min.51ff8c7317566f82259170fa36e09c4493adc9b9378b427a01ad3f017ebac7dd.js"></script>

<script>
    (function (window) {
        var INSIGHT_CONFIG = {
            TRANSLATION: {
                POSTS: 'Posts',
                PAGES: 'Pages',
                CATEGORIES: 'Categories',
                TAGS: 'Tags',
                UNTITLED: '(Untitled)',
            },
            ROOT_URL: 'https:\/\/rulerLwx.gitee.io',
            CONTENT_URL: 'https:\/\/rulerLwx.gitee.io\/searchindex.json ',
        };
        window.INSIGHT_CONFIG = INSIGHT_CONFIG;
    })(window);
</script>
<script type="text/javascript" src="https://rulerLwx.gitee.io/js/insight.min.a343cd9a5a7698336b28ef3a7c16a3a1b1d2d5fb17dc8ed04022bbe08cc5459073a15bdafa3a8a58cdd56080784bdd69fa70b1ae8597565c799c57ed00f0e120.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.min.js"></script>
<script>
    tocbot.init({
        
        tocSelector: '.js-toc',
        
        contentSelector: '.js-toc-content',
        
        headingSelector: 'h1, h2, h3',
        
        hasInnerContainers: true,
    });
</script>

<script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine"></script>
<script type="text/javascript">
    var GUEST = ['nick', 'mail', 'link'];
    var meta = 'nick,mail';
    meta = meta.split(',').filter(function (item) {
        return GUEST.indexOf(item) > -1;
    });
    new Valine({
        el: '#vcomments',
        verify: null ,
        notify: null ,
        appId: 'IyAB0PSPRazTPDxitO1ddQ7O-gzGzoHsz',
        appKey: '5rBJTq4KidYF33eXwvRVhtEH',
        placeholder: 'enjoy~',
        avatar: 'mm',
        meta: meta,
        pageSize: '10' || 10,
        visitor: false 
});
</script>

  </body>
</html>
